// TWDatePicker.m 
// Camera 
// 
// Created by 尚朋 on 2018/10/18. 
// Copyright © 2018年 wzh. All rights reserved. 
// 
// @class  TWDatePicker
// abstract  <#摘要#>
// description  <#描述#>


#import "TWDatePicker.h"
#import "DateModel.h"

@interface TWDatePicker ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSArray *_nameArray;
    
    
}
@property (assign, nonatomic) NSTimeInterval maxSysTimerInterval;
@property (assign, nonatomic) NSTimeInterval minSysTimerInterval;

@property (assign, nonatomic) NSTimeInterval maxTimerInterval;
@property (assign, nonatomic) NSTimeInterval minTimerInterval;


@property (strong, nonatomic) UIPickerView *pickerView;

@property (strong, nonatomic) NSArray *yearArray;
@property (strong, nonatomic) NSArray *monthArray;
@property (strong, nonatomic) NSArray *dayArray;

@property (strong, nonatomic) NSArray *leapMonth;//闰年2月
@property (strong, nonatomic) NSArray *notLeapMonth;//非闰年2月
@property (strong, nonatomic) NSArray *longMonth;//长月
@property (strong, nonatomic) NSArray *shortMonth;//短月

@property (strong, nonatomic) DateModel *currentModel;

@end

@implementation TWDatePicker

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self loadView];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self) {
        [self loadView];
    }
    return self;
}

- (void)loadView{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* maxDate = [inputFormatter dateFromString:@"2099-12-31 23:59:59"];

    
    self.maxSysTimerInterval = [maxDate timeIntervalSince1970];
    self.minSysTimerInterval = 0;
    
    self.minTimerInterval = 0;
    self.maxTimerInterval = NSNotFound;
    
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width/2, 162)];
    
    self.pickerView.backgroundColor = [UIColor whiteColor];
    
    self.pickerView.delegate = self;
    
    self.pickerView.dataSource = self;
    
    [self addSubview:self.pickerView];
    
    self.dayArray = self.longMonth;
    
    [self.pickerView reloadAllComponents];//刷新UIPickerView
    
    
}

- (NSArray *)yearArray{
    if (!_yearArray) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1970; i<2100; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _yearArray = array;
    }
    return _yearArray;
}

- (NSArray *)monthArray{
    if (!_monthArray) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1; i<13; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _monthArray = array;
    }
    return _monthArray;
}
//闰月天数
- (NSArray *)leapMonth{
    if (!_leapMonth) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1; i<30; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _leapMonth = array;
    }
    return _leapMonth;
}

//非闰月天数
- (NSArray *)notLeapMonth{
    if (!_notLeapMonth) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1; i<29; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _notLeapMonth = array;
    }
    return _notLeapMonth;
}

- (NSArray *)longMonth{
    if (!_longMonth) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1; i<=31; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _longMonth = array;
    }
    return _longMonth;
    
}

- (NSArray *)shortMonth{
    if (!_shortMonth) {
        NSMutableArray * array = [NSMutableArray array];
        for (int i = 1; i<=30; i++) {
            [array addObject:[NSString stringWithFormat:@"%d",i]];
        }
        _shortMonth = array;
    }
    return _shortMonth;
    
}
//返回有几列

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{
    if (self.pickerMode == TWDatePickerModeYearAndMonth) {
        return 2;
    }else{
        return 3;
    }
}

//返回指定列的行数

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component==0) {
        return  self.yearArray.count;
    } else if(component==1){
        return  self.monthArray.count;
    }else if (component==2){
        return  self.dayArray.count;
    }
    return [_nameArray count];
}

//返回指定列，行的高度，
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    
    return 45.0f;
}

//返回指定列的宽度

- (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    
    if (self.pickerMode == TWDatePickerModeYearAndMonth) {
        return  self.frame.size.width/2;
    }else{
        
        return  self.frame.size.width/3;
    }

    
    
//    if (component==0) {//iOS6边框占10+10
//        return  self.frame.size.width/3;
//    } else if(component==1){
//        return  self.frame.size.width/3;
//    }
//    return  self.frame.size.width/3;
}



// 自定义指定列的每行的视图，即指定列的每行的视图行为一致

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    if (!view){
        view = [[UIView alloc]init];
    }
    
    CGFloat width;
    if (self.pickerMode == TWDatePickerModeYearAndMonth) {
        width =self.frame.size.width/2;
    }else{
        
        width = self.frame.size.width/3;
    }

    
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, 45)];
    text.font = [UIFont systemFontOfSize:20];
    text.textAlignment = NSTextAlignmentCenter;
    if (component==0) {
        text.text = [NSString stringWithFormat:@"%@",[self.yearArray objectAtIndex:row]];
    }else if (component == 1){
        text.text = [NSString stringWithFormat:@"%@",[self.monthArray objectAtIndex:row]];
    }else{
        text.text = [NSString stringWithFormat:@"%@",[self.dayArray objectAtIndex:row]];
    }
    
    [view addSubview:text];
    
    //隐藏上下直线
   
//    [self.pickerView.subviews objectAtIndex:1].backgroundColor = [UIColor clearColor];
//    [self.pickerView.subviews objectAtIndex:2].backgroundColor = [UIColor clearColor];
    return view;
}

//显示的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        NSString *str = [NSString stringWithFormat:@"%@",[self.yearArray objectAtIndex:row]];
        return str;
    }else if (component == 1){
        NSString *str = [NSString stringWithFormat:@"%@",[self.monthArray objectAtIndex:row]];
        return str;
    }else{
        NSString *str = [NSString stringWithFormat:@"%@",[self.dayArray objectAtIndex:row]];
        return str;
    }
    
    
}

//显示的标题字体、颜色等属性

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *str;
    
    if (component == 0) {
        str = [NSString stringWithFormat:@"%@",[self.yearArray objectAtIndex:row]];
    }else if (component==1){
        str = [NSString stringWithFormat:@"%@",[self.monthArray objectAtIndex:row]];

    }else if (component==2){
        str = [NSString stringWithFormat:@"%@",[self.dayArray objectAtIndex:row]];
    }
    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc]initWithString:str];
    
    [AttributedString addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:12], NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [AttributedString  length])];
    return AttributedString;
    
}//NS_AVAILABLE_IOS(6_0);



//被选择的行

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //判断是否是闰年
    NSInteger year = [pickerView selectedRowInComponent:0]+1970;
    NSInteger month = [pickerView selectedRowInComponent:1]+1;
    if ((year%100==0&&year%400==0) || (year%100!=0&&year%4==0)) {
        //闰年判定：年份是整百数时,能被400整除。或者能被4整除但不能被100整除。其余的年份都为平年。
        //闰年 判断当前年份对应的月份是否是2月 如果是二月 判断是否是闰月 如果不是 赋值 刷新
        if (month==2) {
            if (self.dayArray.count!=29) {
                self.dayArray = self.leapMonth;
                [pickerView reloadComponent:2];
            }
        }else if (month==1||month==3||month==5||month==7||month==8||month==10||month==12){
            if (self.dayArray.count!=31) {
                self.dayArray = self.longMonth;
                [pickerView reloadComponent:2];
            }
        }else{
            if (self.dayArray.count!=30) {
                self.dayArray = self.shortMonth;
                [pickerView reloadComponent:2];
            }
        }
    }else{
        //非闰年 判断当前年份对应的月份是否是2月 如果是二月 判断是否是闰月 如果不是 赋值 刷新
        if (month==2) {
            if (self.dayArray.count!=28) {
                self.dayArray = self.notLeapMonth;
                [pickerView reloadComponent:2];
            }
        }else if (month==1||month==3||month==5||month==7||month==8||month==10||month==12){
            if (self.dayArray.count!=31) {
                self.dayArray = self.longMonth;
                [pickerView reloadComponent:2];
            }
        }else{
            if (self.dayArray.count!=30) {
                self.
                dayArray = self.shortMonth;
                [pickerView reloadComponent:2];
            }
        }
    }
    //拼接成date
    NSString * currentTime = [NSString stringWithFormat:@"%ld-%02ld-%02ld 00:00:00",[pickerView selectedRowInComponent:0]+1970,[pickerView selectedRowInComponent:1]+1,[pickerView selectedRowInComponent:2]+1];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* currentDate = [inputFormatter dateFromString:currentTime];

    [self scrollToDate:currentDate];
}

- (void)setPickerMode:(TWDatePickerMode)pickerMode{
    _pickerMode = pickerMode;
    [self.pickerView reloadAllComponents];
}
- (void)setDate:(NSDate *)date{
    _date = date;
//    self.currentModel.date = date;
    
    [self scrollToDate:_date];
}

- (void)setMaxDate:(NSDate *)maxDate{
    DateModel * model = [[DateModel alloc]init];
    model.date = maxDate;
    
    NSString * currentTime = [NSString stringWithFormat:@"%ld-%02ld-%02ld 23:59:59",model.year,model.month,model.day];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* currentDate = [inputFormatter dateFromString:currentTime];
    _maxDate = currentDate;
  
    if (_maxDate) {
        NSTimeInterval t = [_maxDate timeIntervalSince1970];
        if (t>self.maxSysTimerInterval) {
            t = self.maxSysTimerInterval;
        }else if (t<self.minSysTimerInterval){
            t = self.minSysTimerInterval;
        }
        self.maxTimerInterval = t;
    }
    //刷新当前view
    [self scrollToDate:self.date];

}

- (void)setMinDate:(NSDate *)minDate{
    
    DateModel * model = [[DateModel alloc]init];
    model.date = minDate;
    
    NSString * currentTime = [NSString stringWithFormat:@"%ld-%02ld-%02ld 00:00:00",model.year,model.month,model.day];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* currentDate = [inputFormatter dateFromString:currentTime];
    _minDate = currentDate;
    
    if (_minDate) {
        NSTimeInterval t = [_minDate timeIntervalSince1970];
        if (t>self.maxSysTimerInterval) {
            t = self.maxSysTimerInterval;
        }else if (t<self.minSysTimerInterval){
            t = self.minSysTimerInterval;
        }
        self.minTimerInterval = t;
    }
    //刷新当前view
    [self scrollToDate:self.date];
}

//计算当前应该显示的位置 返回值为当前显示的date
- (void)scrollToDate:(NSDate *)date{
    
    if (date) {
        NSDate * selectDate;
        DateModel * model = [[DateModel alloc]init];
        model.date = date;
        
        NSTimeInterval t = [date timeIntervalSince1970];
        //是否小于当前最小时间  若小于 滚动到最小时间
        if (t<self.minTimerInterval) {
            //当前时间为最小时间 滚动到
            model.date = [NSDate dateWithTimeIntervalSince1970:self.minTimerInterval];
            selectDate = model.date;
            _date = model.date;
            switch (model.monthType) {
                case MonthTimeTypeLeapMonth:
                    self.dayArray = self.leapMonth;
                    break;
                case MonthTimeTypeNotLeapMonth:
                    self.dayArray = self.notLeapMonth;
                    break;
                case MonthTimeTypeLongMonth:
                    self.dayArray = self.longMonth;
                    break;
                case MonthTimeTypeShortMonth:
                    self.dayArray = self.shortMonth;
                    break;
                default:
                    break;
            }
            [self.pickerView reloadComponent:2];
            
        }else if (t>self.maxTimerInterval){
            //是否大于当前的最大时间 若大于 滚动到最大时间

            model.date = [NSDate dateWithTimeIntervalSince1970:self.maxTimerInterval];
            selectDate = model.date;
            _date = model.date;

            switch (model.monthType) {
                case MonthTimeTypeLeapMonth:
                    self.dayArray = self.leapMonth;
                    break;
                case MonthTimeTypeNotLeapMonth:
                    self.dayArray = self.notLeapMonth;
                    break;
                case MonthTimeTypeLongMonth:
                    self.dayArray = self.longMonth;
                    break;
                case MonthTimeTypeShortMonth:
                    self.dayArray = self.shortMonth;
                    break;
                default:
                    break;
            }
            [self.pickerView reloadComponent:2];
            
        }else{
            model.date = date;
            selectDate = model.date;
            _date = model.date;

            switch (model.monthType) {
                case MonthTimeTypeLeapMonth:
                    self.dayArray = self.leapMonth;
                    break;
                case MonthTimeTypeNotLeapMonth:
                    self.dayArray = self.notLeapMonth;
                    break;
                case MonthTimeTypeLongMonth:
                    self.dayArray = self.longMonth;
                    break;
                case MonthTimeTypeShortMonth:
                    self.dayArray = self.shortMonth;
                    break;
                default:
                    break;
            }
            [self.pickerView reloadComponent:2];
            
        }
        
        [self scrollToYear:model.year Month:model.month Day:model.day date:selectDate];
    }
    
}

- (void)scrollToYear:(NSInteger)year
               Month:(NSInteger)month
                 Day:(NSInteger)day
                date:(NSDate *)date{
    
    NSInteger row_year = year-1970;
    NSInteger row_month = month-1;
    NSInteger row_day = day-1;

    [self.pickerView selectRow:row_year inComponent:0 animated:YES];
    [self.pickerView selectRow:row_month inComponent:1 animated:YES];
    [self.pickerView selectRow:row_day inComponent:2 animated:year];

    _selectDate = date;
    if (self.delegate && [self.delegate respondsToSelector:@selector(datePicker:scrollDidEnd:)]) {
        [self.delegate datePicker:self scrollDidEnd:date];
    }
    
    if (self.datePickerBlock) {
        self.datePickerBlock(_selectDate);
    }
}


- (void)layoutSubviews{
    [super layoutSubviews];
    self.pickerView.frame = self.bounds;
}

@end
